/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.util.core;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ContentLocale;
import com.blandware.atleap.persistence.exception.DeleteException;
import com.blandware.atleap.service.core.ContentLocaleManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.service.exception.BeanNotFoundException;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import java.util.Collections;
import java.util.List;

/**
 * <p>Serves as client for content locale manager.
 * Caches lists of available, enabled, active locales and default locale in system.
 * Added in performance reasons, in purpose to avoid redundant calls of methods of ContentLocaleManager, which
 * are controlled by Spring, because such calls often talk to persistence layer even in cases when it is not necessary.
 * </p>
 * <p><a href="LocaleUtil.java.html"><i>View Source</i></a></p>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.7 $ $Date: 2007/12/11 14:23:51 $
 */
public final class LocaleUtil {

	/**
	 * Servlet context key under which instance of this class is saved
	 */
	private static final String INSTANCE_KEY = "com.blandware.atleap.webapp.util.LocaleUtil.INSTANCE";

	/**
	 * All locales available in system
	 */
	private List availableLocales;

    /**
	 * All enabled locales
	 */
	private List enabledLocales;

	/**
	 * Active locales. This is sublist of available locales
	 */
	private List activeLocales;

	/**
	 * Default locale
	 */
	private ContentLocale defaultLocale;

	/**
	 * Content locale manager we're using
	 */
	private ContentLocaleManager contentLocaleManager = null;

	/**
	 * Creates new instance of LocaleUtil and initializes internal fields
	 *
	 * @param servletContext Servlet context
	 */
	private LocaleUtil(ServletContext servletContext) {
		ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		contentLocaleManager = (ContentLocaleManager) applicationContext.getBean(Constants.CONTENT_LOCALE_MANAGER_BEAN);
		synchronizeCache();
	}

	/**
	 * Returns instance of LocaleUtil corresponding to a given servlet context
	 *
     * @param servletContext Servlet context
	 * @return Instance of LocaleUtil
	 */
	public static LocaleUtil getInstance(ServletContext servletContext) {
		LocaleUtil localeUtil = (LocaleUtil) servletContext.getAttribute(INSTANCE_KEY);
		if ( localeUtil == null ) {
			localeUtil = new LocaleUtil(servletContext);
			servletContext.setAttribute(INSTANCE_KEY, localeUtil);
		}
		return localeUtil;
	}

	/**
	 * Creates new locale
	 *
	 * @param locale Content locale to create
	 * @throws BeanAlreadyExistsException if locale with the same identifier already exists
	 */
	public void createContentLocale(ContentLocale locale) throws BeanAlreadyExistsException {
		contentLocaleManager.createContentLocale(locale);
		synchronizeCache();
	}

	/**
	 * Retrieves content locale with specified identifier
	 *
	 * @param identifier Identifier of locale to retrieve
	 * @return Locale with specified identifier or <code>null</code> if none found
	 */
	public ContentLocale retrieveContentLocale(String identifier) {
		return contentLocaleManager.retrieveContentLocale(identifier);
	}

	/**
	 * Updates content locale
	 *
	 * @param locale Content locale to update
	 */
	public void updateContentLocale(ContentLocale locale) {
		contentLocaleManager.updateContentLocale(locale);
		synchronizeCache();
	}

	/**
	 * Deletes locale with specified identifier
	 *
	 * @param identifier Identifier of content locale to delete
	 * @throws BeanNotFoundException if locale with specified identifeir does not exist
	 * @throws DeleteException       if locale could not be deleted
	 */
	public void deleteContentLocale(String identifier) throws BeanNotFoundException, DeleteException {
		contentLocaleManager.deleteContentLocale(identifier);
		synchronizeCache();
	}

	/**
	 * Synchronizes cache with ContentLocaleManager. This method is called after
	 * creating, updating or deleting locale. Such methods are called rarely in production time,
	 * and therefore there is no performance problem
	 */
	public void synchronizeCache() {
        availableLocales = contentLocaleManager.getAvailableLocales();
        enabledLocales = contentLocaleManager.getEnabledLocales();
		activeLocales = contentLocaleManager.getActiveLocales();
		defaultLocale = contentLocaleManager.getDefaultLocale();

		// sort lists
        Collections.sort(availableLocales);
        Collections.sort(enabledLocales);
		Collections.sort(activeLocales);
	}

	/**
	 * Returns list of locales, available in system.
	 *
	 * @return Available locales
	 */
	public List getAvailableLocales() {
		return availableLocales;
	}

    /**
	 * Returns list of all enabled locales.
	 *
	 * @return Enabled locales
	 */
	public List getEnabledLocales() {
		return enabledLocales;
	}

	/**
	 * Returns list of active locales
	 *
	 * @return Active locales
	 */
	public List getActiveLocales() {
		return activeLocales;
	}

	/**
	 * Returns default locale
	 *
	 * @return Default locale
	 */
	public ContentLocale getDefaultLocale() {
		return defaultLocale;
	}

}
